package com.renwei.yunlong.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.work.GuideWebActivity;
import com.renwei.yunlong.activity.work.ObjectSelectActivity;
import com.renwei.yunlong.activity.work.ProjectSelectActivity;
import com.renwei.yunlong.activity.work.ServiceSelectActivity;
import com.renwei.yunlong.adapter.MuchObjectAdapter;
import com.renwei.yunlong.base.BaseFragment;
import com.renwei.yunlong.bean.HandleWorkBean;
import com.renwei.yunlong.bean.AssetBean;
import com.renwei.yunlong.bean.MuchAssetBean;
import com.renwei.yunlong.event.WorkHandlerEvent;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.DateTimeUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.view.WorkDatePopWindow;
import com.zyf.fwms.commonlibrary.base.baseadapter.BaseRecyclerViewAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

import static android.app.Activity.RESULT_OK;

/**
 * Created by wangqi on 2017/11/28.
 */

public class WorkHandlerFragment extends BaseFragment implements BaseRecyclerViewAdapter.OnItemClickLitener, View.OnClickListener, WorkDatePopWindow.onDataSelectListener {

    @Bind(R.id.tv_project)
    TextView tvProject;
    @Bind(R.id.rl_project)
    RelativeLayout rlProject;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.rl_object_add)
    RelativeLayout rlObjectAdd;
    @Bind(R.id.tv_start_time)
    TextView tvStartTime;
    @Bind(R.id.rl_start_time)
    RelativeLayout rlStartTime;
    @Bind(R.id.tv_end_time)
    TextView tvEndTime;
    @Bind(R.id.rl_end_time)
    RelativeLayout rlEndTime;
    @Bind(R.id.et_result_content)
    EditText etResultContent;
    @Bind(R.id.tv_result_number)
    TextView tvResultNumber;
    @Bind(R.id.et_left_content)
    EditText etLeftContent;
    @Bind(R.id.tv_left_number)
    TextView tvLeftNumber;
    @Bind(R.id.et_plan_content)
    EditText etPlanContent;
    @Bind(R.id.tv_plan_number)
    TextView tvPlanNumber;
    private MuchObjectAdapter adapter;
    private String eventId;
    private String requestId;

    private String id; //草稿id
    private String contractId;
    private int mPosition;
    private String ownerCompanyCode;
    private String hardwareIds;
    private WorkDatePopWindow datePopWindow;

    public WorkHandlerFragment() {
    }

    @SuppressLint("ValidFragment")
    public WorkHandlerFragment(String eventId, String requestId, String ownerCompanyCode) {
        this.eventId = eventId;
        this.requestId = requestId;
        this.ownerCompanyCode = ownerCompanyCode;
    }

    public HashMap<String, String> getHandlerData() {
        if (TextUtils.isEmpty(etResultContent.getText().toString())) {
            showCenterInfoMsg("请输入处理结果");
            return null;
        }
        // 时间判断
        if (!TextUtils.isEmpty(tvStartTime.getText().toString()) && !TextUtils.isEmpty(tvEndTime.getText().toString())) {
            if (DateTimeUtils.compareTime(tvEndTime.getText().toString()) <= DateTimeUtils.compareTime(tvStartTime.getText().toString())) {
                showCenterInfoMsg("请选择正确的处理时间");
                return null;
            }
        } else {
            showCenterInfoMsg("请选择处理时间");
            return null;
        }

        for (MuchAssetBean bean : adapter.getData()) {
            for (MuchAssetBean bean1 : adapter.getData()) {
                if (!bean.equals(bean1)) {
                    if (!TextUtils.isEmpty(bean.getAssetId()) && bean.getAssetId().equals(bean1.getAssetId())) {
                        if (TextUtils.isEmpty(bean.getDirectoryId()) && TextUtils.isEmpty(bean1.getDirectoryId())) {
                            showCenterInfoMsg("服务对象和服务目录重复，请重新选择");
                            return null;
                        }
                        if ((!TextUtils.isEmpty(bean.getDirectoryId()) && bean.getDirectoryId().equals(bean1.getDirectoryId()))) {
                            showCenterInfoMsg("服务对象和服务目录重复，请重新选择");
                            return null;
                        }
                    }
                }
            }
        }

        HashMap<String, String> map = new HashMap<>();
        map.put("requestId", requestId);
        map.put("eventId", eventId);
        map.put("result", etResultContent.getText().toString());

        List<HashMap<String, String>> list = new ArrayList<>();
        for (MuchAssetBean bean : adapter.getData()) {
            if (!TextUtils.isEmpty(bean.getAssetId())) {
                HashMap<String, String> objMap = new HashMap<>();
                objMap.put("assetId", bean.getAssetId());
                objMap.put("relationId", bean.getRelationId());
                objMap.put("directoryId", bean.getDirectoryId());
                list.add(objMap);
            }
        }
        String hardWareIds = "";
        if (list.size() != 0) {
            Gson gson = new Gson();
            hardWareIds = gson.toJson(list);
        }

        map.put("hardIds", hardWareIds);
        map.put("id", id);
        map.put("startTime", tvStartTime.getText().toString());
        map.put("endTime", tvEndTime.getText().toString());
        map.put("legacyContent", etLeftContent.getText().toString());
        map.put("followContent", etPlanContent.getText().toString());
        if ("1".equals(companyType)) {
            map.put("ownerCode", ownerBean.getRows().getOwnerCode());
            map.put("currentUserId", ownerBean.getRows().getEmployeeId());
        } else {
            map.put("contractId", contractId);
            map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
            map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
        }
        return map;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_work_handler;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        initView();
    }

    private void initView() {
        etResultContent.setFilters(new InputFilter[]{new InputFilter.LengthFilter(500), AppHelper.emojiFilter});
        etResultContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                tvResultNumber.setText(charSequence.toString().length() + "");
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        etLeftContent.setFilters(new InputFilter[]{new InputFilter.LengthFilter(500), AppHelper.emojiFilter});
        etLeftContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                tvLeftNumber.setText(charSequence.toString().length() + "");
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        etPlanContent.setFilters(new InputFilter[]{new InputFilter.LengthFilter(500), AppHelper.emojiFilter});
        etPlanContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                tvPlanNumber.setText(charSequence.toString().length() + "");
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        rlProject.setOnClickListener(this);
        rlObjectAdd.setOnClickListener(this);
        rlStartTime.setOnClickListener(this);
        rlEndTime.setOnClickListener(this);

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setNestedScrollingEnabled(false);
        adapter = new MuchObjectAdapter(getContext());
        adapter.setOnItemClickLitener(this);
        recyclerView.setAdapter(adapter);

        // 默认一个对象
        adapter.addLastData(new MuchAssetBean());

        if ("1".equals(companyType)) {
            rlProject.setVisibility(View.GONE);
        } else if ("2".equals(companyType)) {
            rlProject.setVisibility(View.VISIBLE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onRefresh(WorkHandlerEvent event) {
        HandleWorkBean handleWorkBean = event.handleWorkBean;
        setData(handleWorkBean);
    }

    private void setData(HandleWorkBean handleWorkBean) {
        if (handleWorkBean.getMessage().getCode() == 200) {
            HandleWorkBean.Rows bean = handleWorkBean.getRows();
            if (bean != null) {
                tvProject.setText(bean.getContractName());
                if (!TextUtils.isEmpty(bean.getStartTime())) {
                    String time = bean.getStartTime().replace("T", " ");
                    tvStartTime.setText(time);
                }
                if (!TextUtils.isEmpty(bean.getEndTime())) {
                    String time = bean.getEndTime().replace("T", " ");
                    tvEndTime.setText(time);
                }
                etResultContent.setText(bean.getContent());
                etLeftContent.setText(bean.getLegacyContent());
                etPlanContent.setText(bean.getFollowContent());

                id = bean.getId();
                contractId = bean.getContractId();
                String hardwareId = bean.getHardwareId();
                List<MuchAssetBean> list = new Gson().fromJson(hardwareId, new TypeToken<List<MuchAssetBean>>() {
                }.getType());

                if (list == null || list.size() == 0) {
                    adapter.clean();
                } else {
                    adapter.setData(list);
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_project: //项目
                hardwareIds = "";
                List<MuchAssetBean> list = adapter.getData();
                for (MuchAssetBean bean : list) {
                    if (!TextUtils.isEmpty(bean.getAssetId())) {
                        hardwareIds += bean.getAssetId() + ",";
                    }
                }
                if (!TextUtils.isEmpty(hardwareIds)) {
                    hardwareIds = hardwareIds.substring(0, hardwareIds.length() - 1);
                }
                ProjectSelectActivity.OpenActivity(this, ownerCompanyCode, contractId, hardwareIds, 555);
                break;
            case R.id.rl_start_time:
                datePopWindow = new WorkDatePopWindow(getActivity(), companyType, requestId, eventId, "开始时间", serviceLoginBean, ownerBean, 333);
                datePopWindow.setListener(this);
                datePopWindow.showAtLocation(getView(), Gravity.BOTTOM, 0, 0);
                break;
            case R.id.rl_end_time:
                datePopWindow = new WorkDatePopWindow(getActivity(), companyType, requestId, eventId, "结束时间", serviceLoginBean, ownerBean, 444);
                datePopWindow.setListener(this);
                datePopWindow.showAtLocation(getView(), Gravity.BOTTOM, 0, 0);
                /*WorkDateSelecterActivity.OpenActivityForResult(this, requestId, eventId, "结束时间", 444);*/
                break;
            case R.id.rl_object_add:
                if (adapter.getItemCount() == 10) {
                    showCenterInfoMsg("最多允许添加10个对象");
                    return;
                }
                adapter.addLastData(new MuchAssetBean());
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Bundle bundle = null;
            if (data != null) {
                bundle = data.getExtras();
            }
            if (requestCode == 111) {  //对象
                boolean isScreen = bundle.getBoolean("isScreen");
                if (isScreen) {
                    // 判断是否为统一公司
                    if (!ownerCompanyCode.equals(bundle.getString("ownerCode"))) {
                        if ("2".equals(companyType)) {
                            tvProject.setText("");
                            contractId = "";
                        }
                    } else {
                        showCenterInfoMsg("该对象不属于当前请求企业");
                        return;
                    }
                }

                MuchAssetBean bean = adapter.getItem(mPosition);
                bean.setAssetName(bundle.getString("name"));
                bean.setAssetId(bundle.getString("hardwareId"));

                bean.setDirectoryName("");
                bean.setDirectoryId("");
                bean.setRelationId("");
                bean.setSolutionState("");

                adapter.notifyItemChanged(mPosition);
            } else if (requestCode == 222) {
                MuchAssetBean bean = adapter.getItem(mPosition);
                if (!TextUtils.isEmpty(bundle.getString("directoryName"))) {
                    bean.setDirectoryName(bundle.getString("directoryName"));
                    bean.setDirectoryId(bundle.getString("directoryId"));
                    bean.setRelationId(bundle.getString("relationIds"));
                }
                if (!TextUtils.isEmpty(bundle.getString("completeTimes")) && !TextUtils.isEmpty(bundle.getString("type"))) {
                    if ("1".equals(bundle.getString("type"))) {
                        bean.setSolutionState(bundle.getString("completeTimes") + "次");
                    } else if ("2".equals(bundle.getString("type"))) {
                        bean.setSolutionState(bundle.getString("completeTimes") + "人/天");
                    }
                } else {
                    bean.setSolutionState("0次");
                }
                adapter.notifyItemChanged(mPosition);
            } else if (requestCode == 333) {//开始时间
                tvStartTime.setText(bundle.getString("time"));
            } else if (requestCode == 444) {//结束时间
                tvEndTime.setText(bundle.getString("time"));
            } else if (requestCode == 555) {//所属项目
                tvProject.setText(bundle.getString("contractName"));
                contractId = bundle.getString("contractId");
                if (!TextUtils.isEmpty(bundle.getString("contractId"))) {
                    if (!TextUtils.isEmpty(hardwareIds)) {
                        // 对象联动
                        getHandwareIds();
                    }
                }
            }
        }
    }

    // 获取服务对象联动
    private void getHandwareIds() {
        HashMap<String, String> map = new HashMap<>();
        map.put("contractId", contractId);
        map.put("hardwareId", hardwareIds);
        map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
        ServiceRequestManager.getManager().getSendWorkHandware(getContext(), JsonMapUtil.mapToJson(map), new HttpTaskListener() {
            @Override
            public void onSuccess(int requestId, String result) {
                AssetBean bean = new Gson().fromJson(result, AssetBean.class);
                List<MuchAssetBean> list = new ArrayList<>();
                if (bean.getRows() != null && bean.getRows().size() != 0) {
                    for (AssetBean.RowsBean rowsBean : bean.getRows()) {
                        for (MuchAssetBean objectBean : adapter.getData()) {
                            if (rowsBean.getAssetId().equals(objectBean.getAssetId())) {
                                list.add(objectBean);
                                break;
                            }
                        }
                    }
                }
                adapter.setData(list);
            }

            @Override
            public void onException(int requestId, String code) {

            }
        });
    }

    @Override
    public void onItemClick(View view, int position) {
        mPosition = position;
        MuchAssetBean bean = adapter.getItem(position);
        switch (view.getId()) {
            case R.id.rl_object_delete: // 删除对象
                if (adapter.getItemCount() > 1) {
                    adapter.removeData(position);
                } else {
                    showCenterInfoMsg("至少需要一个对象");
                }
                break;
            case R.id.rl_object: // 对象
                ObjectSelectActivity.OpenActivity(this, ownerCompanyCode, contractId, 111);
                break;
            case R.id.rl_service: // 服务目录
                if (TextUtils.isEmpty(bean.getAssetId())) {
                    showCenterInfoMsg("请选择服务对象");
                } else {
                    ServiceSelectActivity.OpenActivity(this, ServiceSelectActivity.FROM_WORK_NORMAL, contractId,
                            bean.getAssetId(), ownerCompanyCode, bean.getDirectoryId(), 222);
                }
                break;
            case R.id.tv_title_service:
                GuideWebActivity.openActivity(getContext(), Api.$().$().GUIDE_SERVICE_URI);
                break;
            default:
                break;
        }
    }

    @Override
    public void onErrorMsg(String msg) {
        showTopWrongMsg(msg);
    }

    @Override
    public void onMsg(String msg) {
        showCenterInfoMsg(msg);
    }

    @Override
    public void onSuccessMsg(String msg) {
        showCenterSuccessMsg(msg);
    }

    @Override
    public void onSelectDate(Intent data, int requestCode) {

        Bundle bundle = null;
        if (data != null) {
            bundle = data.getExtras();
        }
        if (requestCode == 111) {  //对象
            boolean isScreen = bundle.getBoolean("isScreen");
            if (isScreen) {
                // 判断是否为统一公司
                if (!ownerCompanyCode.equals(bundle.getString("ownerCode"))) {
                    if ("2".equals(companyType)) {
                        tvProject.setText("");
                        contractId = "";
                    }
                } else {
                    showCenterInfoMsg("该对象不属于当前请求企业");
                    return;
                }
            }

            MuchAssetBean bean = adapter.getItem(mPosition);
            bean.setAssetName(bundle.getString("name"));
            bean.setAssetId(bundle.getString("hardwareId"));

            bean.setDirectoryName("");
            bean.setDirectoryId("");
            bean.setRelationId("");
            bean.setSolutionState("");

            adapter.notifyItemChanged(mPosition);
        } else if (requestCode == 222) {
            MuchAssetBean bean = adapter.getItem(mPosition);
            if (!TextUtils.isEmpty(bundle.getString("directoryName"))) {
                bean.setDirectoryName(bundle.getString("directoryName"));
                bean.setDirectoryId(bundle.getString("directoryId"));
                bean.setRelationId(bundle.getString("relationIds"));
            }
            if (!TextUtils.isEmpty(bundle.getString("completeTimes")) && !TextUtils.isEmpty(bundle.getString("type"))) {
                if ("1".equals(bundle.getString("type"))) {
                    bean.setSolutionState(bundle.getString("completeTimes") + "次");
                } else if ("2".equals(bundle.getString("type"))) {
                    bean.setSolutionState(bundle.getString("completeTimes") + "人/天");
                }
            } else {
                bean.setSolutionState("0次");
            }
            adapter.notifyItemChanged(mPosition);
        } else if (requestCode == 333) {//开始时间
            tvStartTime.setText(bundle.getString("time"));
        } else if (requestCode == 444) {//结束时间
            tvEndTime.setText(bundle.getString("time"));
        } else if (requestCode == 555) {//所属项目
            tvProject.setText(bundle.getString("contractName"));
            contractId = bundle.getString("contractId");
            if (!TextUtils.isEmpty(bundle.getString("contractId"))) {
                if (!TextUtils.isEmpty(hardwareIds)) {
                    // 对象联动
                    getHandwareIds();
                }
            }
        }
    }
}
